<template>
  <div class="dashboard-container">
    <div class="app-container">
      <page-tools :show-before="true">
        <template v-slot:before>
          <span>共{{ total }}条数据</span>
        </template>
        <template v-slot:after>
          <el-button type="primary" @click="$router.push('/import')">
            excel导入
          </el-button>
          <el-button type="primary" @click="exportData">excel导出</el-button>
          <el-button type="primary" @click="showDialog = true">
            新增员工
          </el-button>
        </template>
      </page-tools>
      <el-card>
        <el-table v-loading="loading" border :data="list">
          <el-table-column label="序号" type="index" sortable="" />
          <el-table-column label="姓名" prop="username" sortable="" />
          <el-table-column
            label="头像"
            prop="username"
            width="120px"
            header-align="center"
          >
            <template v-slot="{ row }">
              <img
                v-imagerror="require('@/assets/common/bigUserHeader.png')"
                :src="row.staffPhoto"
                alt=""
                style="width: 100px; height: 100px; border-radius: 50%"
                @click="showQrcode(row.staffPhoto)"
              />
            </template>
          </el-table-column>
          <el-table-column label="工号" prop="workNumber" sortable="" />
          <el-table-column
            label="聘用形式"
            prop="formOfEmployment"
            sortable=""
            :formatter="formatEmployment"
          />
          <el-table-column label="部门" prop="departmentName" sortable="" />
          <el-table-column label="入职时间" prop="timeOfEntry" sortable="">
            <template v-slot="{ row }">
              {{ row.timeOfEntry | formatDate }}
            </template>
          </el-table-column>
          <el-table-column label="账户状态" prop="enableState" sortable="">
            <template slot-scope="{ row }">
              <el-switch
                :value="row.enableState === 1"
                active-color="#13ce66"
                inactive-color="#ff4949"
              >
              </el-switch>
            </template>
          </el-table-column>
          <el-table-column label="操作" sortable="" fixed="right" width="280">
            <template v-slot="{ row }">
              <el-button
                type="text"
                size="small"
                @click="$router.push(`/employees/detail/${row.id}`)"
              >
                查看
              </el-button>
              <el-button type="text" size="small">转正</el-button>
              <el-button type="text" size="small">调岗</el-button>
              <el-button type="text" size="small">离职</el-button>
              <el-button type="text" size="small" @click="checkRole(row.id)">
                角色
              </el-button>
              <el-button
                v-if="checkPermission('point-user-delete')"
                type="text"
                size="small"
                @click="delEmployees(row.id)"
              >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <el-row type="flex" justify="end" style="margin-top: 20px">
          <el-pagination
            :current-page="page.page"
            :total="total"
            :page-size="page.size"
            layout="prev, pager, next"
            @current-change="changePage"
          ></el-pagination>
        </el-row>
      </el-card>
      <add-employee :show-dialog.sync="showDialog"></add-employee>
      <el-dialog :visible.sync="showCodeDialog" title="二维码">
        <el-row type="flex" justify="center">
          <canvas ref="userAvatar"></canvas>
        </el-row>
      </el-dialog>
      <assign-role
        ref="role"
        :show-role-dialog.sync="showRoleDialog"
        :user-id="userId"
      ></assign-role>
    </div>
  </div>
</template>

<script>
import { getEmployeesList, delEmployees } from '@/api/employees'
import employmentStyle from '@/api/constant/employees'
import AddEmployee from './components/AddEmployee'
import { formatDate } from '@/filters'
import qrCode from 'qrcode'
import AssignRole from './components/assign-role'
export default {
  components: { AddEmployee, AssignRole },
  data() {
    return {
      loading: false,
      list: [],
      page: {
        page: 1,
        size: 10
      },
      total: 0,
      showDialog: false,
      showCodeDialog: false,
      showRoleDialog: false,
      userId: ''
    }
  },
  created() {
    this.getEmployeesList()
  },
  methods: {
    async getEmployeesList() {
      this.loading = true
      const result = await getEmployeesList(this.page)
      this.list = result.rows
      this.total = result.total
      this.loading = false
      return result
    },
    changePage(current) {
      this.page.page = current
      this.getEmployeesList()
    },
    formatEmployment(row, column, cellValue, index) {
      // 用单元格的cellValue去匹配employmentStyle.hireType,hirtype是一个数组，通过find方法去匹配数组中值为cellValue的对象
      const obj = employmentStyle.hireType.find((item) => item.id === cellValue)
      return obj ? obj.value : '未知'
    },
    async delEmployees(id) {
      try {
        await this.$confirm('确定删除该员工？')
        await delEmployees(id)
        const res = await this.getEmployeesList()
        console.log(res)
        if (res?.rows.length === 0) {
          this.page.page = Math.ceil(this.total / this.page.size)
          this.getEmployeesList()
        }
        this.$message.success('删除员工成功')
      } catch (error) {
        console.log(error)
      }
    },
    exportData() {
      const headers = {
        姓名: 'username',
        手机号: 'mobile',
        聘用形式: 'formOfEmployment',
        工号: 'workNumber',
        部门: 'departmentName',
        入职日期: 'timeOfEntry',
        转正日期: 'correctionTime'
      }
      // 复杂表头 - 二维数组 - 里面的每一个数组代表一行表头
      const multiHeader = [['姓名', '主要信息', '', '', '', '', '部门']]
      // 合并单元格
      const merges = ['A1:A2', 'B1:F1', 'G1:G2']
      import('@/vendor/Export2Excel').then(async (excel) => {
        const { rows } = await getEmployeesList({ page: 1, size: this.total })
        excel.export_json_to_excel({
          header: Object.keys(headers),
          data: this.formatJSON(headers, rows),
          filename: '员工信息表',
          bookType: 'xlsx',
          autoWidth: true,
          multiHeader, // 复杂表头
          merges // 合并单元格
        })
      })
    },
    // 转化数据的方法
    formatJSON(headers, rows) {
      return rows.map((item) => {
        // item = {name:'zs',mobile:'132'} -> 把key变成中文
        return Object.keys(headers).map((key) => {
          if (key === '入职日期' || key === '转正日期') {
            item[headers[key]] = formatDate(item[headers[key]])
          } else if (key === '聘用形式') {
            const hire = employmentStyle.hireType.find(
              (obj) => obj.id === item[headers[key]]
            )
            hire ? (item[headers[key]] = hire.value) : '未知'
          }
          return item[headers[key]]
        })
      })
    },
    showQrcode(url) {
      this.showCodeDialog = true
      this.$nextTick(() => {
        qrCode.toCanvas(this.$refs.userAvatar, url)
      })
    },
    async checkRole(id) {
      this.userId = id
      await this.$refs.role.getUserDetail(id) // 先请求再显示弹窗 - 避免弹出的一下空白
      this.showRoleDialog = true
    }
  }
}
</script>

<style></style>
